import { useAdminStore } from "../store/admin"
import { APIConstants, getRequest, postRequest } from "../utils/api"

class AdminModels {
    /**
     * 管理员登录
     * @param aname 
     * @param apwd 
     */
    async adminLogin(aname:string, apwd:string){
        let url = APIConstants.ADMIN_LOGIN
        let body = await postRequest(url, {aname, apwd})
        if(body.code===2000 && body.token){     //如果登录成功，需要在客户端缓存用户的身份令牌
            //sessionStorage['loginToken'] = body.token
            //在PiniaStore中存储管理员信息
            const adminStore = useAdminStore()
            adminStore.adminName = aname
            adminStore.adminToken = body.token
        }else {                                 //此次登录失败，应该清除之前保存的身份令牌
            delete sessionStorage['admin']
        }
        return body.code
    }

    /**
     * 获得当前登录的管理员信息
     */
    async adminInfo(){
        let url = APIConstants.ADMIN_INFO
        let body = await getRequest(url, undefined, true)
        return body
    }
}

//对外到处一个单例对象
export const adminModels = new AdminModels()